<template>
	<view class="tabBar-content">
		<view style="margin: 20rpx;">
			<!-- 搜索栏 -->
			<view style="display: flex;justify-content: space-between;">
				<image @click="tabShow = true" src="../../static/images/type.png"
					style="width: 60rpx;height: 60rpx;margin-top: 5rpx;"></image>
				<view @click="onToSearch"
					style="height: 60rpx;border: 3rpx solid #fc6a6c;border-radius: 30rpx;display: flex;justify-content: space-between;line-height: 60rpx;padding: 0 20rpx;width: 560rpx;">
					<text style="color: #ccc;">请输入关键字查询</text>
					<image style="width: 40rpx;height: 40rpx;margin-top: 10rpx;" src="../../static/images/search.png">
					</image>
				</view>
				
			</view>
			<!-- 轮播图 -->
			<view v-if="topAdvertise.length" style="margin-top: 10rpx;">
				<swiper :indicator-dots="false" :autoplay="true" :interval="4000" :circular="true" style="width: 100%;height: 200rpx;">
					<swiper-item v-for="(_item,_index) in topAdvertise" style="width: 100%;height: 200rpx;">
						<image @click="onJump(_item,1)" :src="_item.remoteUrl?_item.remoteUrl:(resourceUrl + _item.img)" style="width: 100%;height: 100%;border-radius: 20rpx;"></image>
					</swiper-item>
				</swiper>
			</view>

			<scroll-view scroll-y @scrolltolower="onLower"
				style="width: 100%;margin-top: 20rpx;" :style="{height:'calc(100vh - var(--window-bottom) - 120rpx - '+(topAdvertise.length ? '210rpx' : '0rem')+')'}">
				<!-- 默认的热门推荐：类型+轮播图+列表页面 -->
				<view v-if="tabIndex === 0">
					<view v-for="(item,index) in recommend" :key="index" style="margin-top: 10rpx;">
						<view style="width: 100%;display: flex;justify-content: space-between;">
							<view style="display: flex;line-height: 50rpx;">
								<image style="width: 50rpx;height: 50rpx;" src="../../static/images/new.png"></image>
								<text style="margin-left: 10rpx;">{{doGetTabName(index).name}}</text>
							</view>
							<view @click="onTab(index,true)" style="color: #999;line-height: 50rpx;font-size: 28rpx;">
								MORE+
							</view>
						</view>
						<!-- 轮播图 -->
						<swiper :indicator-dots="false" :autoplay="true" :interval="(3000 + Math.round(Math.random() * 3000))" :circular="true" style="width: 100%;height: 300rpx;margin-top: 20rpx;">
							<swiper-item v-for="(_item,_index) in item.largePicture" style="width: 100%;height: 300rpx;">
								<image @click="onToVideos(_item)" :src="_item.img" style="width: 100%;height: 100%;border-radius: 20rpx;" mode="aspectFill"></image>
							</swiper-item>
						</swiper>
						<!-- 电影列表 -->
						<view style="display: flex;flex-wrap: wrap;margin-top: 20rpx;">
							<view v-for="(_item,_index) in item.datas" @click="onToVideos(_item)" :key="_index"
								style="width: 335rpx;text-align: center;padding: 10rpx;">
								<image :src="_item.img" style="width: 100%;height: 170rpx;border-radius: 10rpx;" mode="aspectFill"></image>
								<view class="text-ellipsis" style="font-size: 26rpx;">{{_item.name}}</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 靠电影分类搜索出来的列表页面 -->
				<view v-else>
					<view style="width: 100%;display: flex;justify-content: space-between;">
						<view style="display: flex;line-height: 50rpx;">
							<image style="width: 50rpx;height: 50rpx;" src="../../static/images/new.png"></image>
							<text style="margin-left: 10rpx;">{{doGetTabName(tabs[tabIndex]._id).name}}</text>
						</view>
					</view>
					<view style="display: flex;flex-wrap: wrap;">
						<view v-for="(item,index) in datas" :key="index" @click="onToVideos(item)"
							style="width: 335rpx;text-align: center;padding: 10rpx;">
							<image :src="item.img" style="width: 100%;height: 170rpx;border-radius: 10rpx;" mode="aspectFill"></image>
							<view class="text-ellipsis" style="font-size: 26rpx;">{{item.name}}</view>
						</view>
					</view>
				</view>
				<view v-if="bottomAdvertise.img || bottomAdvertise.remoteUrl" style="height: 120rpx;" />
			</scroll-view>

			<!-- 类型弹框 -->
			<view v-show="tabShow" @click="tabShow = false"
				style="width: 100vw;height: calc(100vh - var(--window-bottom));position: absolute;top: 0;right: 0;z-index: 100;background-color: rgba(0, 0, 0, 0.5);">
				<view style="width: 40vw;height: calc(100% - var(--status-bar-height));background-color: #ffffff;border-radius: 0 20rpx 20rpx 0;padding-top: var(--status-bar-height);float: right;">
					<scroll-view scroll-y style="height: 100%;" :scroll-top="tabScroll">
						<view v-for="(item,index) in tabs" :key="index" @click.stop="onTab(index)"
							:class="(index === tabIndex ? 'tab-selected' : 'tab') + ' scroll-item text-center'">
							{{item.name}}
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		<view v-if="bottomAdvertise.img || bottomAdvertise.remoteUrl" @click="onJump(bottomAdvertise,1)" style="position: absolute;width: 100vw;height: 100rpx;bottom: 0;left: 0;z-index: 99;background-color: black">
			<image :src="bottomAdvertise.remoteUrl?bottomAdvertise.remoteUrl:(resourceUrl + bottomAdvertise.img)" style="width: 100%;height: 100%;"></image>
		</view>
		<MyUseOut :showModal="isUseOut" @close="isUseOut=false" />
		<tui-toast ref="toast"></tui-toast>
	</view>

</template>

<script>
	import {configData,popularity,recommendVideos,typeVideos,configTypes} from '@/api/home.js'
	export default {
		data() {
			return {
				isUseOut: false,
				tabShow: false,
				tabs: [],
				tabIndex: 0,
				tabScroll: 0,

				recommend: {},
				// 当前分页
				page: 1,
				// 总共数据数量
				count: 1,
				// 详细数据
				datas: [],
				// 顶部广告
				topAdvertise:[],
				// 广告
				bottomAdvertise: {},
			}
		},
		onLoad() {
			// 如果是从本页面的MyUseOut弹框进入三种增加次数的页面去了，并且成功后，再跳转到本页面要默认关闭弹窗
			uni.$on('closeModal',data=>{
				this.isUseOut=data
			})
		},
		onShow() {
			this.doGetTabs();
			this.doGetAdvertise();
		},
		onUnload() {
			// 页面销毁时移除监听，防止重复绑定
			uni.$off('closeModal');
		},
		// 下拉刷新
		onPullDownRefresh() {
			if (this.tabIndex === 0) {
				this.doGetRecommendVideos();
			} else {
				this.page = 1;
				this.datas = [];
				this.count = 1;
				this.doGetTypeVideos();
			}
		},
		methods: {
			doGetAdvertise(){
				configData({type:3}).then(res => {
					this.topAdvertise = res.data.advertise.top || [];
					this.bottomAdvertise = res.data.advertise.bottom || {};
				})
			},
			/**
			 * 跳转
			 * @param {Object} item
			 * @param {Object} type  1：广告，2：app
			 */
			onJump(item,type){
				let url = item.href;
				popularity({type,_id:item._id})
				let isApp = true;
				// #ifdef H5
					isApp = false;
				// #endif
				if(isApp){
					plus.runtime.openURL(url)
				}else{
					if(/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) {
						window.location.href = url;
					} else {
						window.open(url);
					} 
				}
			},
			/**
			 * tab切换
			 * @param {Object} index
			 */
			onTab(index, isRecommend) {
				if (isRecommend) {
					let tab = this.doGetTabName(index);
					if (tab.index === -1) {
						return;
					}
					index = tab.index;
				}
				const query = uni.createSelectorQuery().in(this);
				let that = this;
				this.tabIndex = index;
				query
					.selectAll(`.scroll-item`)
					.boundingClientRect(rect => {
						const windowHeight = uni.getSystemInfoSync().safeArea.height - 60 // 屏幕宽度
						let height = 0,
							tabScroll = 0;
						// 循环获取计算当前点击的标签项距离左侧的距离
						for (let i = 0; i < index; i++) {
							height += rect[i].height
						}
						// 当大于屏幕一半的宽度则滚动，否则就设置位置为0
						if (height > windowHeight / 2) {
							tabScroll = height + rect[index].height / 2 - windowHeight / 2
						} else {
							tabScroll = 0
						}
						that.tabScroll = tabScroll;
						that.tabShow = false;
						// 获取数据
						if (index !== 0) {
							that.page = 1;
							that.datas = [];
							that.count = 1;
							that.doGetTypeVideos();
						} else {
							that.doGetRecommendVideos();
						}
					}).exec()
			},
			// 获取类型数据
			doGetTabs() {
				configTypes().then(res => {
					this.tabs = [{
						name: "热门推荐"
					}, ...res.data,{_id:"-1",name:"其他"}];
					this.doGetRecommendVideos();
				})
			},
			// 获取推荐视频
			doGetRecommendVideos() {
				recommendVideos().then(res => {
					this.recommend = res.data || {};
					console.log(333,this.recommend );
					uni.stopPullDownRefresh();
				})
			},
			// 分类数据到底
			onLower() {
				if (this.tabIndex !== 0 && this.datas.length < this.count) {
					this.page += 1;
					this.doGetTypeVideos();
				}else{
					this.showTips()
				}
			},
			showTips(e) {
				let options = {
					title: '我是有底线的啦~',
					icon: false
				};
				//需等组件初始化完成，确认已获取到组件实例
				this.$refs.toast && this.$refs.toast.show(options);
			},
			// 获取分类视频
			doGetTypeVideos() {
				typeVideos( {
					type: this.tabs[this.tabIndex]._id,
					page: this.page
				}).then(res => {
					this.datas.push(...res.data.data);
					this.count = res.data.count;
					uni.stopPullDownRefresh();
				})
			},
			// 前往查看视频
			onToVideos(item) {
				if (!uni.getStorageSync('infinite')) {
					this.isUseOut = true
					return
				}
				uni.navigateTo({
					url:"/pages/watchMovie/videos?id=" + item._id
				})
			},
			// 前往搜索页面
			onToSearch(){
				uni.navigateTo({
					url:"/pages/watchMovie/search"
				})
			},
			// 获取视频分类的名称
			doGetTabName(_id) {
				let name = "",
					index = -1;
				for (let i = 0; i < this.tabs.length; i++) {
					if (this.tabs[i]._id === _id) {
						index = i;
						name = this.tabs[i].name;
						break;
					}
				};
				return {
					name,
					index
				}
			}
		},

	}
</script>

<style scoped>
	page{
		overflow-y: hidden;
	}
	.tab-selected {
		padding: 20rpx 30rpx;
		background: linear-gradient(rgb(16, 79, 252), rgb(255, 120, 160));
		/* border-radius: 20rpx; */
		color: white;
		font-weight: bold;
		white-space: nowrap;
	}

	.tab {
		padding: 15rpx 30rpx;
		white-space: nowrap;
	}
</style>